/**
 * Mockcat Server
 * @author Wangtd
 */
const http = require('http');
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const cookieParser = require("cookie-parser");

const config = require('./config.js');
const util = require('./lib/util.js');
const mocker = require('./lib/mocker.js');
const router = require('./lib/router.js');
const security = require('./lib/security.js');

var app = express();

// cookie & session
app.use(cookieParser());
app.use(session({
    secret: 'mockcat',
    cookie: { maxAge: 30 * 60 * 1000 },// 30 minutes
    resave: false,
    saveUninitialized: true
}));

// blog
util.mkdirsSync(util.path(config.blogDir, 'images'));
util.mkdirsSync(util.path(config.blogDir, 'articles'));
util.writeFileSync(config.blogDir + '/blogs.json', JSON.stringify({
    categories: [],
    articles: []
}, null, 2));
app.use('/app/blog', express.static(config.blogDir));
// app
app.use('/app', express.static(util.paths(config.debug ? 'app' : 'dist')));
// parameter
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ type: 'application/json', limit: '5mb' }));
// security
util.writeFileSync(config.workDir + '/users.json', '[]');
app.use(['/mock/module/*', '/mock/data/*', '/mock/blog/*'], security.checkPermission);
// router
app.use(router);
// mock
util.mkdirsSync(config.mockDir);
app.use('/', mocker.mock(config.mockDir));

// start http server
http.createServer(app).listen(config.port, '0.0.0.0', function(error) {
    if (error) {
        console.error(error);
    } else {
        console.log('Mockcat server is running at http://localhost:%d/', config.port);
    }
});
